package com.cabinet.db;

import com.cabinet.Config;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: denny
 * Date: 10/2/13
 * Time: 7:08 PM
 * To change this template use File | Settings | File Templates.
 */
@XmlRootElement(name = "locations")
public class DBLocations {
  List<DBLocation> allLocations = new ArrayList<>();

  public static DBLocations loadFromDiskDB() throws Exception{
    File dbFile = Config.locationsDB();
    if( dbFile.canRead() ){
      JAXBContext jc = JAXBContext.newInstance(DBLocations.class);
      return (DBLocations)jc.createUnmarshaller().unmarshal(dbFile);
    }else{
      return null;
    }
  }

  public void add(DBLocation loc){
    allLocations.add(loc);
  }

  public void save() throws Exception{
    JAXBContext jc = JAXBContext.newInstance(DBLocations.class);
    Marshaller jaxbMarshaller = jc.createMarshaller();
    // output pretty printed
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.marshal(this, Config.locationsDB());
  }

  
  public DBLocation findByDevId(long devId){
    for( DBLocation l : allLocations ){
      if( devId==l.devId ){
        return l;
      }
    }
    return null;
  }

  @XmlElement(name = "loc")
  public List<DBLocation> getAllLocations() {
    return allLocations;
  }

  public void setAllLocations(List<DBLocation> allLocations) {
    this.allLocations = allLocations;
  }
}
